"""
@author: j.l.liu
@create: 
@description: 创建一个Streamlit简单应用，命令行后执行：streamlit run app.py
"""
import requests
import streamlit as st

st.title("Streamlit简单应用")
# 创建文件上传控件
# 创建文件上传控件，支持多种文件类型
uploaded_file = st.file_uploader("上传文件", type=["csv", "txt", "pdf", "png", "jpg", "jpeg", "mp3", "wav", "mp4", "avi", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "zip", "rar", "json"])

# 检查是否有文件上传
if uploaded_file is not None:
    st.write(f"上传的文件名: {uploaded_file.name}")
    # 根据文件类型处理文件
    if uploaded_file.name.endswith((".csv", ".txt", ".json")):
        # 处理文本文件
        content = uploaded_file.read().decode("utf-8")
        st.write("文件内容：")
        st.text(content)
    elif uploaded_file.name.endswith((".png", ".jpg", ".jpeg")):
        # 处理图片文件
        st.image(uploaded_file, width=250)
    elif uploaded_file.name.endswith(".pdf"):
        # 处理 PDF 文件
        import PyPDF2
        pdf_reader = PyPDF2.PdfReader(uploaded_file)
        st.write("PDF 文件内容：")
        for page_num in range(len(pdf_reader.pages)):
            page = pdf_reader.pages[page_num]
            st.write(f"第 {page_num + 1} 页：")
            st.text(page.extract_text())
    elif uploaded_file.name.endswith((".mp3", ".wav")):
        # 处理音频文件
        st.audio(uploaded_file)
    elif uploaded_file.name.endswith((".mp4", ".avi")):
        # 处理视频文件
        st.video(uploaded_file)
    else:
        st.write("文件类型不支持预览。")

# 创建文本输入控件
user_input = st.text_input("您请输入文本：")
if st.button("提交"):
    # 将用户输入发送到fastapi后端
    response = requests.post("http://127.0.0.1:8000/submit/", json={"input_text": user_input})
    if response.status_code == 200:
        st.write("后端响应：", response.json())
    else:
        st.error("请求失败")
elif st.button("读取"):
    # 获取后台返回的信息
    response = requests.get("http://127.0.0.1:8000/read/")
    if response.status_code == 200:
        st.write("后端响应：", response.json())
    else:
        st.error("请求失败")
